package com.dong.module.foodmenu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dong.common.util.FileUtils;
import com.dong.module.foodmenu.dao.FoodMenuMapper;
import com.dong.module.foodmenu.pojo.FoodMenu;
import com.dong.module.foodmenu.service.FoodMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description:
 * @author: 陈瑞东
 * @create: 2021-08-25 08:36
 */
@Service
public class FoodMenuServiceImpl extends ServiceImpl<FoodMenuMapper, FoodMenu> implements FoodMenuService {

    @Autowired
    private FoodMenuMapper foodMenuMapper;

    @Override
    public void save(String id, String name, String filename) {
        // id 为空则为添加操作
        if (StringUtils.isBlank(id)) {
            FoodMenu foodMenu = new FoodMenu(name, filename, null, null);
            id = String.valueOf(IdWorker.getId(foodMenu));
            foodMenu.setId(id);
            String destFilename = FileUtils.saveImage(id, filename);
            foodMenu.setImage(destFilename);
            save(foodMenu);
        } else {
            FoodMenu foodMenu = getById(id);
            if (foodMenu == null) {
                throw new RuntimeException("菜单不存在！");
            }
            // 设置名字
            foodMenu.setName(name);
            if (!foodMenu.getImage().equals(filename)) {
                // 设置文件名
                String destFilename = FileUtils.saveImage(id, filename);
                foodMenu.setImage(destFilename);
            }
            updateById(foodMenu);
        }
    }

    @Override
    public List<FoodMenu> listFood(int current, int size, String name) {
        Page<FoodMenu> page = new Page<>(current, size);
        QueryWrapper<FoodMenu> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        queryWrapper.orderByDesc("CREATE_TIME");
        Page<FoodMenu> foodMenuPage = foodMenuMapper.selectPage(page, queryWrapper);
        return foodMenuPage.getRecords();
    }

    @Override
    public void saveDetail(String id, String ingredients, String practice) {
        FoodMenu foodMenu = getById(id);
        if (foodMenu == null) {
            throw new RuntimeException("菜单不存在！");
        }
        // 判断此次修改的字段，设置修改的字段
        if (StringUtils.isNotBlank(ingredients)) {
            foodMenu.setIngredients(ingredients);
        } else if (StringUtils.isNotBlank(practice)) {
            foodMenu.setPractice(practice);
        }
        updateById(foodMenu);
    }
}
